<template>
  <div class="mod-config">
    <basic-container>
      <div class="boxsty">
        <div class="flex justifyContentSpaceBetween">
          <div class="tabletext">测评关系管理</div>
          <div class="tablelink">

            <el-link icon="el-icon-plus" type="primary" v-if="permissions.cpgzgl_cepingcpgzgzxxb_add"
              @click="gzxx_addOrUpdateHandle($event,null)" :underline="false">新增关系</el-link>
          </div>
        </div>
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()" class="form-inline">
          <el-form-item label="关系名称">
            <el-input v-model="dataForm.gzName" style="width:300px" placeholder="请输入关系名称进行检索"></el-input>
          </el-form-item>
          <el-form-item label="关系状态">
            <el-select :clearable="true" v-model="dataForm.gzZt" placeholder="请选择状态" style="margin-left:10px"
              class="xiaLa">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-button icon="el-icon-search" type="primary" class="marginLeft" @click="getDataList1()">检索</el-button>
          </el-form-item>
        </el-form>
        <div class="avue-crud" style="max-height:60vh">
          <el-collapse v-model="activeName" v-for="(item,index) in dataList" :key="index"
            @change="querySubRuleHandler(item.id,index)" accordion>
            <el-collapse-item>
              <template slot="title">
                <!-- <div class="collapseCheckbox">
                  <el-checkbox @change="copyById($event,item.id,index)"></el-checkbox>
                </div> -->
                <div class="collapseBox">

                  <div class="collapseBox">
                    <div class="flex alignItemsCenter"><span class="numTip">{{ index + 1 }}</span>
                      <span class="titleBox">{{item.gzName}}</span>
                      <el-popover placement="top-start" width="450" trigger="hover">
                        <div class="font18">{{ item.gzName}}关系说明</div>
                        <div class="font16">
                          {{item.gzSm}}
                        </div>
                        <el-button slot="reference" type="text" icon="el-icon-warning" v-if="item.gzSm != 0"
                          style="margin-left:10px">关系说明</el-button>
                      </el-popover>
                    </div>

                    <div class="collapseSummary flex justifyContentSpaceBetween">
                      <div>
                        <!-- <div>创建时间：{{$moment(item.createTime).format("YYYY-MM-DD")}}</div> -->
                        <div class="mb5"><span>被测评对象：{{item.gzBpfdx}}</span><span class="marginLeft">评票权重：{{item.gzQz}}</span><span class="marginLeft">评票票数：{{item.gzPs}}</span></div>
                        <div><span>关系状态：<span :class="ZtYy(item.gzZt)">{{item.gzZt === 0 ? '隐藏' : '显示'}}</span></span><span class="marginLeft">验证标记：<span :class="Zt(item.gzYz)">{{item.gzYz}}</span></span></div>

                      </div>
                      <div>
                        <el-button type="primary" plain
                          @click="updateRuleOrShowOrNoneHandler( $event,item.id,item.gzZt)">
                          {{ item.gzZt == '1' ? '隐藏' : '显示' }}
                        </el-button>
                        <el-button type="primary" plain @click="gzxx_UpdateAndCopy($event,item.id)">复用</el-button>
                        <el-button type="primary" plain v-if="permissions.cpgzgl_cepingcpgzgzxxb_edit"
                          @click="gzxx_addOrUpdateHandle($event,item.id)">编辑关系</el-button>
                        <el-button type="danger" plain v-if="permissions.cpgzgl_cepingcpgzgzxxb_del"
                          @click="gzxx_deleteHandle($event,item.id)">删除关系</el-button>
                      </div>
                    </div>
                  </div>

                </div>
              </template>
              <div align="right" style="margin:10px 0;">
                <el-button type="primary" plain v-if="permissions.cpgzgl_cepingcpgzgzxxb_add&&item.bcpmxbsubList&&item.bcpmxbsubList.length==0"
                           @click="cpoy_remarkObject(item,index)">引用被测评对象</el-button>
                <el-button type="primary" plain v-if="permissions.cpgzgl_cepingcpgzgzxxb_add" ref="xzcpdx"
                  @click="add_remarkObject(item,index)">新增被测评对象</el-button>
              </div>
              <div class="avue-crud">
              <el-table :current-row-key="index" :data="item.bcpmxbsubList" stripe>
                <el-table-column label="部门名称" v-if="item.gzBpfdx ==='部门'" prop="deptName"></el-table-column>
                <el-table-column label="人员名称" v-else prop="userName"></el-table-column>
                <el-table-column label="排序号" prop="bcpPx">
                  <template slot-scope="scope">
                    <div v-if="!scope.row.upSort" class="flex alignItemsCenter">
                      <label style="margin-right:10px">{{scope.row.bcpPx}}</label>
                      <el-button type="text" @click="editSotr(scope.store.table.currentRowKey,scope.$index,true)">编辑
                      </el-button>
                    </div>
                    <div v-else class="flex alignItemsCenter">
                      <el-input-number v-model="pbcpPx" :min="1" :max="10000" style="margin-right:10px">
                      </el-input-number>
                      <el-button type="primary" plain @click="updateSort(scope.row.id)">保存</el-button>
                      <el-button type="danger" plain
                        @click="editSotr(scope.store.table.currentRowKey,scope.$index,false)">取消</el-button>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="300">
                  <template slot-scope="scope">
                    <el-button type="danger" plain v-if="permissions.cpgzgl_cepingcpgzgzxxb_del"
                      @click="bcpmx_deleteHandle(scope.row.id,scope.store.table.currentRowKey,scope.$index,scope.row.gzId)">
                      删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              </div>
              <!-- 凭票详情 -->
              <div align="right" style="margin:10px 0;">
                <el-button type="primary" plain v-if="permissions.cpgzgl_cepingcpgzgzxxb_add"
                  @click="gzmx_addOrUpdateHandle($event,item.id,null,index)">新增测评对象</el-button>
              </div>
              <el-table :current-row-key="index" :data="item.cpmxbList" style="width: 100%;" stripe>
                <el-table-column label="评票编号" prop="cpCode" width="150"></el-table-column>
                <el-table-column label="评票名称" prop="cpName"></el-table-column>
                <el-table-column label="评票权重" prop="cpQz"></el-table-column>
                <el-table-column label="是否实名" prop="isSm"></el-table-column>
                <el-table-column label="评票票数" prop="cpPs"></el-table-column>
                <el-table-column label="操作" fixed="right" width="300">
                  <template slot-scope="scope">
                    <el-button type="primary" plain v-if="permissions.ceping_cepinggzxxb_add"
                      @click="gzxxConfig(scope.row.gzId, scope.row.id,scope.row.isSm)">配置</el-button>
                    <el-button type="primary" plain v-if="permissions.cpgzgl_cepingcpgzgzxxb_edit"
                      @click="gzmx_addOrUpdateHandle($event ,scope.row.gzId, scope.row.id,scope.store.table.currentRowKey)">
                      编辑</el-button>
                    <el-button type="danger" plain v-if="permissions.cpgzgl_cepingcpgzgzxxb_del"
                      @click="gzmx_deleteHandle(scope.row.id,scope.store.table.currentRowKey,scope.$index,scope.row.gzId,scope.row.cpPs)">
                      删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

            </el-collapse-item>
          </el-collapse>
        </div>
        <div class="avue-crud__pagination">
        <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
                       :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" background
                       layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>
      </div>


      <!--被测评人是人员-->
      <usercomment v-if="usercommentVisibal" ref="usercomment_Select" @showRemarkList="showRemarkObject" @closeDialogComp="closeDialogComp"></usercomment>
      <!--被测评人是部门-->
      <deptcomment v-if="deptcommentVisibal" ref="deptcomment_Select" @showRemarkList="showRemarkObject" @closeDialogComp="closeDialogComp"></deptcomment>
      <!--   关系信息   -->
      <cepingcpgzgzxxbForm v-if="gzxx_addOrUpdateVisible" ref="gzxx_addOrUpdate" @refreshDataList="getDataList" @closeCPGX="closeCPGX">
      </cepingcpgzgzxxbForm>
      <cepingcpgzcpmxbForm v-if="gzmx_addOrUpdateVisible" ref="gzmx_addOrUpdate" @refGzmxList="refGzmxList" @closeCPDX="closeCPDX">
      </cepingcpgzcpmxbForm>

      <!-- 关系匿名 -->
      <gznmForm v-if="gznmVisibal" ref="refGznmFrom" @refPzGzmx="refPzGzmx"></gznmForm>
      <!-- 关系实名 -->
      <gzsmFrom v-if="gzsmVisibal" ref="refGzsmFrom" @refPzGzmx="refPzGzmx"></gzsmFrom>
      <!-- 关系引用 -->
      <gzyyFrom ref="gzyyFrom" @showRemarkList="getDataList"></gzyyFrom>
    </basic-container>
  </div>
</template>

<script>
  /**
   * 绩效考核_测评_评分关系管理列表
   * @author zgc
   * @date 2021-06-16 10:06:44
   */
  import {
    fetchList,
    delObj,
    cepingcpgzgzxxbCopyRule,
    updateCpgzGzxxbShowOrNone,
    updateGzYz
  } from '@/api/ceping/cepingcpgzgzxxb'
  import {
    getBcpmxb,
    delBcpmxbObj,
    putObj
  } from '@/api/ceping/cepingcpgzbcpmxb'
  import {
    getCepingMx,
    gzmxdelObj
  } from '@/api/ceping/cepingcpgzcpmxb'
  import cepingcpgzgzxxbForm from './cepingcpgzgzxxb-form'
  import cepingcpgzcpmxbForm from './cepingcpgzcpmxb-form'
  import usercomment from "./usercomment";
  import deptcomment from "./deptcomment";
  import gznmForm from "./gznmForm"; //关系匿名
  import gzsmFrom from "./gzsmForm"; //关系实名
  import gzyyFrom from "./gzyyForm"; //关系引用
  import {
    mapGetters
  } from 'vuex';
  import {
    Message
  } from 'element-ui';

  export default {
    data() {
      return {
        isSer: 0,
        pbcpPx: 1,
        dataForm: {
          gzName: '',
          gzZt: '1'
        },
        options: [{
          value: '1',
          label: '显示'
        }, {
          value: '0',
          label: '隐藏'
        }],
        activeName: '',
        dataList: [],

        mxUpdateOrAddPid: '',
        copyIdList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        gzmx_addOrUpdateVisible: false,
        gzxx_addOrUpdateVisible: false,
        usercommentVisibal: false,
        deptcommentVisibal: false,
        addOrUpdateDataIndex: '', //数据更新或插入索引值全局使用该索引
        gznmVisibal: false,
        gzsmVisibal: false,

        //检查关系是否通过或异常  默认刷新
        checkRefresh: true

      };
    },
    components: {
      cepingcpgzgzxxbForm,
      cepingcpgzcpmxbForm,
      usercomment,
      deptcomment,
      gznmForm,
      gzsmFrom,
      gzyyFrom
    },
    created() {
      this.getDataList();

    },
    computed: {
      ...mapGetters(['permissions'])
    },
    methods: {
      getDataList1() {
        this.isSer = 1;
        this.getDataList();
      },
      disableKeyEnterEvent(ids){
        for(var i = 0;i<ids.length;++i){
          var el = this.$refs[ids[i]] && this.$refs[ids[i]].$el
          if(el){

            el.onkeydown= (e) =>{
              let _key=window.event.keyCode;
              if(_key===13){
                return false;
              }
            }
          }

        }

      },
      //关系信息业务
      // 获取数据列表
      getDataList() {
        this.gzxx_addOrUpdateVisible=false;
        //回调不刷新
        if (this.checkRefresh) {
          this.activeName = '';
        }

        this.dataListLoading = true;
        fetchList(Object.assign({
          current: this.pageIndex,
          size: this.pageSize,
        }, this.dataForm)).then(response => {
          this.dataList = response.data.data.records;
          this.totalPage = response.data.data.total;
          if (this.isSer == 0) {
            if (this.mxUpdateOrAddPid) {
              console.log('1')
              //关系为通过的时候刷新数据
                this.refGzMxb();
                this.refBcpdxb();
            }
            this.isSer = 0;
          }
          this.$forceUpdate();

        });
        this.checkRefresh = true;
        this.dataListLoading = false;


      },
      //关闭测评关系表单
      closeCPGX(){
        this.gzxx_addOrUpdateVisible=false;
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val;
        this.pageIndex = 1;
        this.getDataList();
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val;
        this.getDataList();
      },
      // 新增 / 修改
      gzxx_addOrUpdateHandle(event, id) {
        this.mxUpdateOrAddPid = '';
        event.stopPropagation();
       //console.log('来着');
       //console.log('this.gzxx_addOrUpdateVisible',this.gzxx_addOrUpdateVisible)
        if(!this.gzxx_addOrUpdateVisible){
         //console.log('回车不该来')
          this.gzxx_addOrUpdateVisible = true;
          this.$nextTick(() => {
            this.$refs.gzxx_addOrUpdate.init(id, null);
          });
        }
      },
      //新增关系并且拷贝
      gzxx_UpdateAndCopy(event, id) {
        this.mxUpdateOrAddPid = '';
        event.stopPropagation();
        if(!this.gzxx_addOrUpdateVisible) {
          this.gzxx_addOrUpdateVisible = true;
          this.$nextTick(() => {
            this.$refs.gzxx_addOrUpdate.init(id, true);
          });
        }
      },
      //是否有子项
      async gzxxHaveRecords(pid) {
        let bResult = false;

        list: {
          await getBcpmxb(pid).then(rss => {
            if (rss.data.data.length > 0) {
              bResult = true;
            }
          })

          if (bResult) {
            break list;
          }

          //查询关系明细列表
          await getCepingMx(pid).then(rs => {
            if (rs.data.data.length > 0) {
              bResult = true;
            }
          })
        }

        return bResult;
      },
      // 删除
      gzxx_deleteHandle(event, id) {
        event.stopPropagation();
        this.gzxxHaveRecords(id).then(res => {
          if (res) {
            this.$notify.closeAll();
            this.$notify.error("存在下一级无法删除");
          } else {
            this.$confirm('是否确认删除', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(function () {
              return delObj(id);
            }).then(data => {
              this.$notify.closeAll();
              this.$notify.success('删除成功');
              this.getDataList();
            }).catch((err)=>{
              console.log(err)
            });
          }
        });
      },
      //  关系拷贝
      copyById(event, id, index) {
        if (event == true) {
          this.copyIdList[index] = id;
        } else if (event == false) {
          this.copyIdList.splice(index, 1);
        }
      },
      //提交拷贝
      copyRuleHandler() {
        var ruleIdList = [];
        for (var i = 0; i < this.copyIdList.length; i++) {
          if (this.copyIdList[i]) {
            ruleIdList.push(this.copyIdList[i]);
          }
        }
        if (this.copyIdList.length == 0) {
          this.$notify.closeAll();
          this.$notify.error("请选择要拷贝的关系");
          return;
        } else {
          cepingcpgzgzxxbCopyRule(ruleIdList).then(data => {
            this.$notify.closeAll();
            this.$notify.success('拷贝成功');
            this.copyIdList = [];
            this.getDataList();
          }).catch(() => {
            this.$notify.closeAll();
            this.$notify.error("拷贝失败");
          });
        }
      },
      //状态
      ZtYy(value) {
        return {
          yinCang: value === 0,
          green: value === 1,
          // blue: value === "002",
          // green: value === "003",
        };
      },

      //状态
      Zt(value) {
        return {
          red: value === "异常",
          green: value === "通过",
        };
      },
      /**
       * 修改关系显示或隐藏
       */
      updateRuleOrShowOrNoneHandler(event, ruleId, gzzt) {
        var data = {
          ruleId: ruleId,
          gzZt: gzzt == 1 ? 0 : 1
        };
        event.stopPropagation();
        updateCpgzGzxxbShowOrNone(data).then(data => {
          this.$notify.closeAll();
          this.$notify.success('修改成功');
          this.getDataList();
        }).catch(() => {
          this.$notify.closeAll();
          this.$notify.error("修改失败");
        });
      },
      //  关系明细业务
      //关系明细 新增 / 修改
      gzmx_addOrUpdateHandle(event, gzId, mxId, index) {
        event.stopPropagation();
        var _this = this;
        this.mxUpdateOrAddPid = gzId;
        this.addOrUpdateDataIndex = index;
        if(!_this.gzmx_addOrUpdateVisible){
          _this.gzmx_addOrUpdateVisible = true;
          _this.$nextTick(() => {
            _this.$refs.gzmx_addOrUpdate.init(gzId, mxId);
          });
        }
      },
      onEnterPress(){
       //console.log('回车事件')
      },
      //被测评人删除
      bcpmx_deleteHandle(id, praIndex, subIndex, gzId) {
        var _this = this;
        this.$confirm('是否确认删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          _this.dataList[praIndex].bcpmxbsubList.splice(subIndex, 1);
          _this.$forceUpdate();
          return delBcpmxbObj(id);
        }).then(data => {
          this.$notify.closeAll();
          this.$notify.success('删除被测评对象成功');
          this.mxUpdateOrAddPid = gzId;
          this.casGzxxGetGzYz(gzId);
        });

      },
      //关系明细 删除
      gzmx_deleteHandle(id, praIndex, subIndex, gzId, cpPs) {
        if (cpPs > 0 && cpPs) {
          this.$notify.closeAll();
          this.$notify.error("已配置测评人，不允许删除");
        } else {
          var _this = this;
          this.$confirm('是否确认删除', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(function () {
            return gzmxdelObj(id);
          }).then(data => {
            if (data.data.data) {
              _this.dataList[praIndex].cpmxbList.splice(subIndex, 1);
              _this.$forceUpdate();
              this.$notify.closeAll();
              this.$notify.success('删除成功');
              this.casGzxxGetGzYz(gzId);
            } else {
              this.$notify.closeAll();
              this.$notify.error(data.data.msg);
            }

          }).catch((err)=>{
            console.log(err)
          });
        }

      },
      //加载关系分值
      querySubRuleHandler(pid, index) {
        //接受全局数据索引
        this.addOrUpdateDataIndex = index;
        this.mxUpdateOrAddPid = pid;
        var _this = this;
        //查询关系明细列表
        getCepingMx(pid).then(response => {
          _this.$set(_this.dataList[index], 'cpmxbList', response.data.data);

        }).catch(() => {
          this.$notify.closeAll();
          this.$notify.error("关系分值查询失败");
        });
        //查询被测评对象列表
        getBcpmxb(pid).then(response => {
          var arr = response.data.data
          for (var i = 0; i < arr.length; i++) {
            this.$set(arr[i], 'upSort', false)
          }
          _this.$set(_this.dataList[index], 'bcpmxbsubList', arr);
        }).catch(() => {
          this.$notify.closeAll();
          this.$notify.error("加载被测评人员失败");
        });
      },
      //新增关系明显更新后回调函数
      refGzmxList() {
        this.gzmx_addOrUpdateVisible=false;
        this.casGzxxGetGzYz(this.mxUpdateOrAddPid);
      },
      //关闭测评关系表单
      closeCPDX(){
        this.gzmx_addOrUpdateVisible=false;
      },
      //添加测评人员后回调查询关系是否通过
      refPzGzmx() {
        this.casGzxxGetGzYz(this.mxUpdateOrAddPid);
      },
      //增加被测评对象
      add_remarkObject(item, index) {
        this.mxUpdateOrAddPid = item.id;
        this.addOrUpdateDataIndex = index;
        if (item.gzBpfdx === '部门' && !this.deptcommentVisibal) {
          this.deptcommentVisibal = true;
          this.$nextTick(() => {
            this.$refs.deptcomment_Select.init(item.id);
          });
        }
        if (item.gzBpfdx === '个人' && !this.usercommentVisibal) {
          this.usercommentVisibal = true;
          this.$nextTick(() => {
            this.$refs.usercomment_Select.init(item.id);
          });
        }
      },
      cpoy_remarkObject(item, index){
        this.mxUpdateOrAddPid = item.id;
        this.addOrUpdateDataIndex = index;
        this.$refs.gzyyFrom.init(item.id,item.gzBpfdx)
      },
      //被测评对象成功回调
      showRemarkObject() {
        this.closeDialogComp();
        this.casGzxxGetGzYz(this.mxUpdateOrAddPid)
      },
      //关闭被测评关系弹框
      closeDialogComp(){
        this.deptcommentVisibal=false;
        this.usercommentVisibal=false;
      },
      //格式化日期
      stateFormat(row, column) {
        return this.$moment(row.createTime).format("YYYY-MM-DD");
      },
      //查询或者更新配置信息表
      gzxxConfig(gzId, mxid, isSm) {
        if (isSm === '实名') {
          this.gzsmVisibal = true;
          this.$nextTick(() => {
            this.$refs.refGzsmFrom.init(gzId, mxid)
          });
        }
        if (isSm === '匿名') {
          this.gznmVisibal = true;
          this.$nextTick(() => {
            this.$refs.refGznmFrom.init(gzId, mxid)
          });
        }
      },
      //检查关系是否通过或异常
      casGzxxGetGzYz(gzId) {
        updateGzYz(gzId).then(response => {
          this.checkRefresh = false;
            Promise.all([
              this.getDataList()
            ]).then((res) => {
              this.refGzMxb();
              this.refBcpdxb();
              console.log(res)
            }).catch(err=>{
              console.log(err);
            })
          // this.getDataList();
          // this.refGzMxb();
          // this.refBcpdxb();
        }).catch(() => {
          this.$notify.closeAll();
          this.$notify.error("数据异常");
        });
      },
      //刷新被测评对象
      refBcpdxb() {
        getBcpmxb(this.mxUpdateOrAddPid).then(response => {
          var arr = response.data.data
          if (arr.length > 0) {
            this.$set(this.dataList[this.addOrUpdateDataIndex], 'bcpmxbsubList', response.data.data);
          }
          this.$forceUpdate();
          console.log("3，",this.dataList)
        }).catch(() => {
          this.$notify.closeAll();
          this.$notify.error("加载被测评人员失败");
        });
      },
      //心中测评人员后验
      refGzMxb() {
        var _this = this;
        getCepingMx(_this.mxUpdateOrAddPid).then(response => {
          var arr = response.data.data
          if (arr.length > 0) {
            _this.$set(_this.dataList[_this.addOrUpdateDataIndex], 'cpmxbList', response.data.data);
          }
          this.$forceUpdate();
          console.log("2，",this.dataList)
        }).catch(() => {
          this.$notify.closeAll();
          this.$notify.error("关系分值查询失败");
        });
      },
      //编辑排序
      editSotr(pIndex, subIndex, isUp) {
        if (isUp) {
          this.$set(this.dataList[pIndex].bcpmxbsubList[subIndex], 'upSort', isUp);
        } else {
          this.pbcpPx = 1;
          this.$set(this.dataList[pIndex].bcpmxbsubList[subIndex], 'upSort', isUp);
        }

      },
      //更新排序
      updateSort(id) {
        putObj({
          id: id,
          bcpPx: this.pbcpPx
        }).then(response => {
          this.pbcpPx = 1;
          this.checkRefresh = false;
          this.getDataList();
          this.$notify.success("修改成功");
        }).catch(() => {
          this.$notify.error("数据错误")
        });
      }

    }
  };

</script>
